from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from rest_framework.generics import ListAPIView

from .models import Question, Reply, Label
from .question_serializers import QuestionModelSerializer, ReplyModelSerializer

from question.paginations import MyPage
from question.serializers import LabelsSerializer,QuestionSerializer

from rest_framework.views import APIView
from django_redis import get_redis_connection
import json

from .models import Question, Reply


class QuestionView1(ModelViewSet):
    queryset = Question.objects.all()
    serializer_class = QuestionModelSerializer

    def my_retrieve(self, request, pk):
        """问题详情"""

        instance = self.get_object()
        serializer = self.get_serializer(instance)

        replyset_0 = Reply.objects.filter(problem=serializer.data['id'], type=0)
        reply_serializer_0 = ReplyModelSerializer(replyset_0, many=True)

        replyset_2 = Reply.objects.filter(problem=serializer.data['id'], type=2)
        reply_serializer_2 = ReplyModelSerializer(replyset_2, many=True)

        for _dict in reply_serializer_2.data:
            replyset_1 = Reply.objects.filter(parent=_dict['id'], type=1)
            reply_serializer_1 = ReplyModelSerializer(replyset_1, many=True)

            _dict['subs'] = reply_serializer_1.data

        data = {**serializer.data}
        data['comment_question'] = reply_serializer_0.data
        data['answer_question'] = reply_serializer_2.data

        return Response(data)


class LabelsView(ListAPIView):

    serializer_class = LabelsSerializer
    queryset = Label.objects.all()
    # pagination_class = MyPage

#关于问题视图接口

#获取最新问题
class QuestionView(ListAPIView):
    serializer_class = QuestionSerializer
    queryset = Question.objects.all()
    # pagination_class = MyPage

    def get_new_question(self, request, pk):

        if pk =="-1":
            questions = Question.objects.all().order_by("-replytime")
        else:
            label = Label.objects.get(id=pk)
        questions = label.questions.all().order_by("-replytime")
        serializer = QuestionSerializer(instance=questions, many=True)
        return Response(serializer.data)


#获取最热门问题
class HotQuestionView(ListAPIView):
    serializer_class = QuestionSerializer
    queryset = Question.objects.all()
    # pagination_class = MyPage

    def get_hot_question(self, request, pk):

        if pk == "-1":
            questions = Question.objects.all().order_by("-reply")
        else:
            label = Label.objects.get(id=pk)
        questions = label.questions.all().order_by("-reply")
        serializer = QuestionSerializer(instance=questions, many=True)
        return Response(serializer.data)

#获取等待回答的问题
class WaitQuestionView(ListAPIView):
    serializer_class = QuestionSerializer
    queryset = Question.objects.all()
    # pagination_class = MyPage
    def get_wait_question(self, request, pk):

        if pk == "-1":
            questions = Question.objects.all()
        else:
            label = Label.objects.get(id=pk)
            questions = label.questions.all()
        questions = questions.filter(reply=0).order_by("-createtime")
        serializer = QuestionSerializer(instance=questions, many=True)
        return Response(serializer.data)


# 问题有用
class QuestionRoleView(APIView):
    def put(self, request, id):
        # 业务处理
        user = request.user
        conn = get_redis_connection('default')
        question = Question.objects.get(pk=id)
        # redis判断用户是否已点击
        users = conn.smembers('question_%s' % question.id)
        if user.id in [int(i) for i in users]:
            return Response({'message': '请勿重复操作', 'success': False})
        # mysql提交数据
        question.useful_count += 1
        question.save()
        # 使用redis添加标记
        conn.sadd('question_%s' % question.id, user.id)  # b'12'
        # 响应
        return Response({'message': '操作成功', 'success': True})


# 问题无用
class QuestionUnRoleView(APIView):
    def put(self, request, id):
        # 业务处理
        user = request.user
        conn = get_redis_connection('default')
        question = Question.objects.get(pk=id)
        # redis判断用户是否已点击
        users = conn.smembers('questionunrole_%s' % question.id)
        if user.id in [int(i) for i in users]:
            return Response({'message': '请勿重复操作', 'success': False})
        # mysql提交数据
        question.unuseful_count += 1
        question.save()
        # 使用redis添加标记
        conn.sadd('questionunrole_%s' % question.id, user.id)  # b'12'
        # 响应
        return Response({'message': '操作成功', 'success': True})


# 回答有用
class ReplyRoleView(APIView):
    def put(self, request, id):
        # 业务处理
        user = request.user
        conn = get_redis_connection('default')
        reply = Reply.objects.get(pk=id)
        # redis判断用户是否已点击
        users = conn.smembers('reply_%s' % reply.id)
        if user.id in [int(i) for i in users]:
            return Response({'message': '请勿重复操作', 'success': False})
        # mysql提交数据
        reply.useful_count += 1
        reply.save()
        # 使用redis添加标记
        conn.sadd('reply_%s' % reply.id, user.id)  # b'12'
        # 响应
        return Response({'message': '操作成功', 'success': True})


# 回答无用
class ReplyUnRoleView(APIView):
    def put(self, request, id):
        # 业务处理
        user = request.user
        conn = get_redis_connection('default')
        reply = Reply.objects.get(pk=id)
        # redis判断用户是否已点击
        users = conn.smembers('replyunrole_%s' % reply.id)
        if user.id in [int(i) for i in users]:
            return Response({'message': '请勿重复操作', 'success': False})
        # mysql提交数据
        reply.unuseful_count += 1
        reply.save()
        # 使用redis添加标记
        conn.sadd('replyunrole_%s' % reply.id, user.id)  # b'12'
        # 响应
        return Response({'message': '操作成功', 'success': True})


# 回答问题
class AnswerQuestion(APIView):
    def post(self, request):
        # 获取参数
        user = request.user
        data = json.loads(request.body.decode())
        problem = data.get('problem')
        content = data.get('content')
        type = str(data.get('type'))
        parent = data.get('parent')

        # 校验
        if not all([problem, content, type]):
            return Response({'message': '缺少参数', 'success': False})

        # 业务处理
        question = Question.objects.get(pk=problem)
        # 1、评论问题
        if type == '0':
            question.replies.create(
                problem=question.id,
                user=user,
                content=content,
                type=type
            )
            return Response({'message': '评论成功', 'success': True})

        # 2、回答问题
        elif type == '2':
            Reply.objects.create(
                problem=question,
                user=user,
                content=content,
                type=type,
            )
            return Response({'message': '回答成功', 'success': True})

        # 3、评论回答
        elif type == '1':
            Reply.objects.create(
                problem=question,
                user=user,
                content=content,
                type=type,
                parent=Reply.objects.get(pk=parent)
            )
            return Response({'message': '回答成功', 'success': True})

